package com.taiyi.renaissancemall.wxapi

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import com.taiyi.renaissancemall.Utils.ToastUtils
import com.taiyi.renaissancemall.Utils.Utils
import com.taiyi.renaissancemall.base.MyApp
import com.taiyi.renaissancemall.bean.BaseResultBean
import com.taiyi.renaissancemall.bean.BindOpenIdBean
import com.taiyi.renaissancemall.net.BaseUrl
import com.taiyi.renaissancemall.net.HttpUtils
import com.taiyi.renaissancemall.net.callbck.JsonCallback
import com.taiyi.renaissancemall.ui.MainActivity
import com.taiyi.renaissancemall.ui.login.BindWechatActivity
import com.taiyi.renaissancemall.ui.mine.withdraw.WithdrawEvent
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.first_fragment_layout.*
import okhttp3.*
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import java.io.IOException

class WXEntryActivity : AppCompatActivity(), IWXAPIEventHandler {
    companion object {
        var type = 1
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        supportActionBar?.hide();
        // 隐藏状态栏
        getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        );
        //接收到分享以及登录的intent传递handleIntent方法，处理结果
        var iwxapi = WXAPIFactory.createWXAPI(this, "wx54586503773d580c", false);
        iwxapi.handleIntent(getIntent(), this);

//        setContentView(R.layout.activity_w_x_entry)
    }

    override fun onResp(p0: BaseResp?) {
        when (p0?.errCode) {
            BaseResp.ErrCode.ERR_OK -> {
                if (type == 1) {//微信登录
                    var resp = p0 as SendAuth.Resp
                    var code = resp.code
                    Log.i("wxapi", "------code------")
                    getOpenId(code)
                } else if (type == 2) {//分享到朋友-调取获取积分接口
                    EventBus.getDefault().post("shareProductSuccess")
                    finish()
                }
            }
            BaseResp.ErrCode.ERR_AUTH_DENIED -> {
                Log.i("wxapi", "------用户拒绝授权------")
                //用户拒绝授权
                finish()
            }
            BaseResp.ErrCode.ERR_USER_CANCEL -> {
                Log.i("wxapi", "------用户取消------")
                //用户取消
                finish()
            }
            else ->
                finish()
        }

    }

    fun getOpenId(code: String) {
        var sb = StringBuffer()
        sb.append("https://api.weixin.qq.com/sns/oauth2/access_token")
            .append("?appid=")
            .append("wx54586503773d580c")
            .append("&secret=")
            .append("9b46118f9241fb1bcc938f61841d7187")
            .append("&code=")
            .append(code)
            .append("&grant_type=authorization_code")
        var okHttpClient = OkHttpClient()
        var request = Request.Builder().url(sb.toString()).get().build()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {

            }

            override fun onResponse(call: Call, response: Response) {
                var responseInfo = response.body()?.string()
                Log.d("qqq",responseInfo)
                var jsonObject = JSONObject(responseInfo)
                var openId = jsonObject.optString("openid")
                var accessToken = jsonObject.getString("access_token")
                if (2 == MyApp.getOpenId) {
                    EventBus.getDefault().post(WithdrawEvent(openId, accessToken))
                    finish()
                } else {
                    bindOpenId(openId)
                }
            }

        })

    }

    fun bindOpenId(openId: String) {
        var map = mutableMapOf<String, String>()
        map.put("weiuserid", openId)
        HttpUtils.postRequest(
            BaseUrl.BIND_WECHAT_OPENID,
            this,
            map,
            object : JsonCallback<BaseResultBean<BindOpenIdBean>>() {
                override fun convertResponse(response: Response?): BaseResultBean<BindOpenIdBean> {
                    return super.convertResponse(response)
                }

                override fun onSuccess(response: com.lzy.okgo.model.Response<BaseResultBean<BindOpenIdBean>>?) {
                    super.onSuccess(response)
                    if (response?.body()?.code == 0) {
                        var data = response.body().data
                        var token = data.token
                        Utils.getSpUtils()
                            .putString("token", token)
                        var tel = response.body().data.tel
                        if (tel == null || tel == "") {
                            var intent =
                                Intent(this@WXEntryActivity, BindWechatActivity::class.java)
                            startActivity(intent)
                        } else {
                            var intent =
                                Intent(this@WXEntryActivity, MainActivity::class.java)
                            startActivity(intent)
                        }
                        finish()
                    } else {
                        ToastUtils.showLongToast(response?.body()?.msg_cn)
                        finish()
                    }
                }

                override fun onError(response: com.lzy.okgo.model.Response<BaseResultBean<BindOpenIdBean>>?) {
                    super.onError(response)
                }
            })
    }


    override fun onReq(p0: BaseReq?) {

    }
}


